package com.yuhj.cateyemovie.fragment;

import java.util.ArrayList;
import java.util.List;

import com.lidroid.xutils.BitmapUtils;
import com.yuhj.cateyemovie.R;
import com.yuhj.cateyemovie.adapter.WillPlayMovieAdapter;
import com.yuhj.cateyemovie.bean.Advertisement;
import com.yuhj.cateyemovie.bean.PlayingMovieList;
import com.yuhj.cateyemovie.clients.ClientApi;
import com.yuhj.cateyemovie.interfaces.AdvertisementCallback;
import com.yuhj.cateyemovie.interfaces.PlayingMovieCallback;
import com.yuhj.cateyemovie.utils.LoadingAinm;
import com.yuhj.cateyemovie.widget.PinnedSectionListView.PinnedSectionListAdapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @name WillPlayingFragment
 * @Descripation 已经上映的影片 <br>
 * @author 禹慧军
 * @date 2014-10-31
 * @version 1.0
 */
public class WillPlayingFragment extends Fragment {
	private ListView listView;
	private Context context;
	private WillPlayMovieAdapter adapter;
	private String city = "北京";
	private RelativeLayout loadRelativeLayout;
	ArrayList<PlayingMovieList> favorite = new ArrayList<PlayingMovieList>();
	ArrayList<PlayingMovieList> thisWeek = new ArrayList<PlayingMovieList>();
	ArrayList<PlayingMovieList> nextWeek = new ArrayList<PlayingMovieList>();
	ArrayList<ArrayList<PlayingMovieList>> data = new ArrayList<ArrayList<PlayingMovieList>>();
	private String Url = "http://api.mobile.meituan.com/dianying/v4/movies.json?tp=coming&order=show_desc&ct="
			+ city
			+ "&utm_campaign=AmovieBmovieC110189035512576D-1&movieBundleVersion=100&utm_source=wandoujia&utm_medium=android&utm_term=100&utm_content=352706060172190&ci=1&uuid=A1A230538BAA987DFF805E95D3B8D53EAB6025EC580F2C6C56CF303DD5BB5A2E";
	private boolean falg = true;
	private int imageLength;
	private ViewPager viewPager; // android-support-v4中的滑动组件
	private List<ImageView> imageViews; // 滑动的图片集合
	private String[] titles; // 图片标题
	private TextView tv_title;
	private int currentItem = 0; // 当前图片的索引号
	private int[] Num = null;
	private int Count = 0;

	public WillPlayingFragment() {
		context = getActivity();
		// TODO Auto-generated constructor stub
	}

	private Handler handler = new Handler() {
		@SuppressWarnings("unchecked")
		public void handleMessage(android.os.Message msg) {
			if (msg == null) {
				Toast.makeText(context, "网络异常，请检查", 1).show();
				loadRelativeLayout.setVisibility(View.GONE);
			} else {
				loadRelativeLayout.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				if (msg.what == 1) {
					favorite = (ArrayList<PlayingMovieList>) msg.obj;
					adapter.upfavorite(favorite);
					adapter.notifyDataSetChanged();

					System.out.println("-------favorite" + favorite.size());
				} else if (msg.what == 2) {
					thisWeek = (ArrayList<PlayingMovieList>) msg.obj;
					adapter.upthisWeek(thisWeek);
					adapter.notifyDataSetChanged();
					System.out.println("-------thisweek" + thisWeek.size());
				} else if (msg.what == 3) {
					nextWeek = (ArrayList<PlayingMovieList>) msg.obj;
					adapter.upnextWeek(nextWeek);
					adapter.notifyDataSetChanged();
					System.out.println("-------nextweek" + nextWeek.size());
				}
				listView.setAdapter(adapter);

			}

		};

	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.will_play_fragment, null, false);
		listView = (ListView) view.findViewById(R.id.willPlay_listview);
		View headView = headerView();
		if (headView!=null) {
			listView.addHeaderView(headerView());
		}
		loadRelativeLayout = (RelativeLayout) view
				.findViewById(R.id.lodingRelativeLayout);
		adapter = new WillPlayMovieAdapter(getActivity());
		LoadingAinm.ininLodingView(view);

		new Thread(new Runnable() {

			@Override
			public void run() {
				ClientApi.getPlayingMovieData(Url, "first",
						new PlayingMovieCallback() {

							@Override
							public void getresult(
									ArrayList<PlayingMovieList> result) {
								Message msMessage = Message.obtain();
								msMessage.obj = result;
								msMessage.what = 1;
								handler.sendMessage(msMessage);

							}
						});
				ClientApi.getPlayingMovieData(Url, "second",
						new PlayingMovieCallback() {

							@Override
							public void getresult(
									ArrayList<PlayingMovieList> result) {
								Message msMessage = Message.obtain();
								msMessage.obj = result;
								msMessage.what = 2;
								handler.sendMessageDelayed(msMessage,2000);

							}
						});
				ClientApi.getPlayingMovieData(Url, "third",
						new PlayingMovieCallback() {
							@Override
							public void getresult(
									ArrayList<PlayingMovieList> result) {
								Message msMessage = Message.obtain();
								msMessage.obj = result;
								msMessage.what = 3;
								handler.sendMessageDelayed(msMessage,3000);

							}
						});

			}
		}).start();
		return view;
	}

	View headerView() {
		final View view = LayoutInflater.from(getActivity()).inflate(
				R.layout.imagebox, null);
		final ArrayList<Fragment> fragments = new ArrayList<Fragment>();
		new Thread(new Runnable() {

			@Override
			public void run() {

				ClientApi.getAdvertisement(new AdvertisementCallback() {

					@Override
					public void getresult(ArrayList<Advertisement> result) {
						if (result != null) {
							imageLength = result.size() * 2 - 1;
							int len = result.size();

							Num = new int[2 * len - 1];
							for (int i = 0; i < Num.length; i++) {
								if (i < len) {
									Num[i] = i;
								} else {
									Num[i] = 2 * len - 2 - i;
								}

							}

							titles = new String[len];
							imageViews = new ArrayList<ImageView>();
							for (int i = 0; i < result.size(); i++) {
								titles[i] = result.get(i).getName();
							}
							// 初始化图片资源
							for (int i = 0; i < len; i++) {

								fragments.add(new ImageFragment(result.get(i)
										.getImg(), getActivity()));

							}
							tv_title = (TextView) view
									.findViewById(R.id.tv_title);
							tv_title.setText(titles[0]);//
							viewPager = (ViewPager) view.findViewById(R.id.vp);
							viewPager.setAdapter(new ImagePageAdapter(
									getChildFragmentManager(), fragments));// 设置填充ViewPager页面的适配器
							// 设置一个监听器，当ViewPager中的页面改变时调用
							viewPager
									.setOnPageChangeListener(new MyPageChangeListener());
						}
					}
				});

			}

		}).start();

		return view;

	}

	public void onStart() {

		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				while (falg) {
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (imageLength > 0) {

						Count++;
						currentItem = Num[(Count) % imageLength];
						// System.out.println("---"+imageLength+"-curretn :>" +
						// currentItem);
						// handler.obtainMessage().sendToTarget(); //
						// 通过Handler切换图片

						Message msg = Message.obtain();
						msg.obj = currentItem;
						handlerTime.sendMessage(msg);
					}
				}
			}
		}).start();

		super.onStart();

	}

	@Override
	public void onStop() {
		// 当Activity不可见的时候停止切换
		falg = false;
		super.onStop();
	}

	// 切换当前显示的图片
	private Handler handlerTime = new Handler() {
		public void handleMessage(android.os.Message msg) {
			viewPager.setCurrentItem((Integer) msg.obj);
		};
	};

	/**
	 * 当ViewPager中页面的状态发生改变时调用
	 * 
	 * @author Administrator
	 * 
	 */
	private class MyPageChangeListener implements OnPageChangeListener {

		/**
		 * This method will be invoked when a new page becomes selected.
		 * position: Position index of the new selected page.
		 */
		public void onPageSelected(int position) {
			tv_title.setText(titles[position]);
			currentItem = position;
		}

		public void onPageScrollStateChanged(int arg0) {

		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}
	}

	/**
	 * 填充ViewPager页面的适配器
	 * 
	 * @author Administrator
	 * 
	 */
	private class ImagePageAdapter extends FragmentPagerAdapter {
		private ArrayList<Fragment> data;

		public ImagePageAdapter(FragmentManager fm, ArrayList<Fragment> data) {
			super(fm);
			this.data = data;
		}

		@Override
		public Fragment getItem(int arg0) {
			return data.get(arg0);
		}

		@Override
		public int getCount() {
			return data.size();
		}

	}


}
